package com.example.controller;

import com.example.dao.ScoreCrudRepository;
import com.example.dao.UserCrudRepository;
import com.example.pojo.LearningSituation;
import com.example.pojo.Score;
import com.example.pojo.PageBean;
import com.example.pojo.User;
import com.example.pojo.vo.LearningSituationDTO;
import com.example.pojo.vo.LearningSituationVo;
import com.example.pojo.vo.ScoreVo;
import com.example.tools.JwtUtils;
import com.example.tools.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/score")
@Slf4j
public class ScoreController {
    @Autowired
    private ScoreCrudRepository scoreCrudRepository;
    @Autowired
    private UserCrudRepository userCrudRepository;

    @PostMapping("/addScore")
    public Result add(Integer trainingPlanId, String score, @RequestHeader("token") String token) {
        Integer id = JwtUtils.parseJWT(token).get("id", Integer.class);
        User user = userCrudRepository.findById(id).get();

        Score save = scoreCrudRepository.save(new Score(null, user.getId(), trainingPlanId, score));
        return Result.success(save);
    }


    @GetMapping("/getScoreByTrainingPlanIdAndUserId")
    public Result getScoreByTrainingPlanIdAndUserId(Integer trainingPlanId, Integer userId) {
        scoreCrudRepository.getScoreByTrainingPlanIdAndUserId(trainingPlanId, userId);
        return Result.success();
    }

    @GetMapping("/getMyScoreByTrainingPlanId")
    public Result getScoreByTrainingPlanId(Integer trainingPlanId, @RequestHeader("token") String token) {
        Integer id = JwtUtils.parseJWT(token).get("id", Integer.class);
        User user = userCrudRepository.findById(id).get();

        scoreCrudRepository.getScoreByTrainingPlanIdAndUserId(trainingPlanId, user.getId());
        return Result.success();
    }


    @PostMapping("/getExamSituationOfOnePlan")
    public Result getExamSituationOfOnePlan(@RequestBody LearningSituationDTO learningSituationDTO,
                                            @RequestParam(defaultValue = "1") Integer page,
                                            @RequestParam(defaultValue = "10") Integer pageSize) {
        //log.info("learningSituationDTO,{}",learningSituationDTO);
        Integer trainingPlanId = learningSituationDTO.getTrainingPlanId();
        if (trainingPlanId == null) {
            return Result.error("请先选择培训计划");
        }
        Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.Direction.ASC, "id");
        //查询满足条件的所有学员
        List<User> allStudent = new ArrayList<>();
        Page<User> userPage = userCrudRepository.findAll(new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //获取条件对象
                Predicate predicate = cb.conjunction();
                //判断用户对象
                if (learningSituationDTO != null) {
                    // 根据 user 的属性添加查询条件
                    if (learningSituationDTO.getName() != null) {
                        predicate.getExpressions().add(cb.like(root.get("name"), "%" + learningSituationDTO.getName() + "%"));
                    }
                    predicate.getExpressions().add(cb.equal(root.get("role"), "学员"));
                    if (learningSituationDTO.getAgencyId() != null) {
                        predicate.getExpressions().add(cb.equal(root.get("agencyId"), learningSituationDTO.getAgencyId()));
                    }
                }
                return predicate;
            }
        }, pageable);
        allStudent = userPage.getContent();
        List<ScoreVo> scoreList = new ArrayList();
        //查询参数计划下的所有学员对应的学习记录
        for (User user : allStudent) {
            Score score = scoreCrudRepository.getScoreByTrainingPlanIdAndUserId(trainingPlanId, user.getId());
            String score1 = null;
            if (score != null) {
                score1 = score.getScore();
            }
            ScoreVo scoreVo = new ScoreVo(user.getId(), trainingPlanId, user.getName(), user.getAgencyId(), score1);
            scoreList.add(scoreVo);
        }
        long elements = userPage.getTotalElements();
        return Result.success(new PageBean(elements, scoreList));
    }


    @PostMapping("/getExamSituationList")
    public Result getExamSituationList(@RequestBody LearningSituationDTO learningSituationDTO) {
        //log.info("learningSituationDTO,{}",learningSituationDTO);
        Integer trainingPlanId = learningSituationDTO.getTrainingPlanId();
        if (trainingPlanId == null) {
            return Result.error("请先选择培训计划");
        }
        //查询满足条件的所有学员
        List<User> allStudent = userCrudRepository.findAll(new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //获取条件对象
                Predicate predicate = cb.conjunction();
                //判断用户对象
                if (learningSituationDTO != null) {
                    // 根据 user 的属性添加查询条件
                    if (learningSituationDTO.getName() != null) {
                        predicate.getExpressions().add(cb.like(root.get("name"), "%" + learningSituationDTO.getName() + "%"));
                    }
                    predicate.getExpressions().add(cb.equal(root.get("role"), "学员"));
                    if (learningSituationDTO.getAgencyId() != null) {
                        predicate.getExpressions().add(cb.equal(root.get("agencyId"), learningSituationDTO.getAgencyId()));
                    }
                }
                return predicate;
            }
        });
        List<ScoreVo> scoreList = new ArrayList();
        //查询参数计划下的所有学员对应的学习记录
        for (User user : allStudent) {
            Score score = scoreCrudRepository.getScoreByTrainingPlanIdAndUserId(trainingPlanId, user.getId());
            String score1 = null;
            if (score != null) {
                score1 = score.getScore();
            }
            ScoreVo scoreVo = new ScoreVo(user.getId(), trainingPlanId, user.getName(), user.getAgencyId(), score1);
            scoreList.add(scoreVo);
        }

        return Result.success(scoreList);
    }

}
